package _dp_base;

/**
 * 931. 下降路径最小和
 */
public class No931 {
    private int[][] matrix;
    private int[][] cache;

    /**
     * 1. 递归
     */
    public int minFallingPathSum1(int[][] matrix) {
        this.matrix = matrix;
        int n = matrix.length;
        if (n == 1) return matrix[0][0];
        cache = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cache[i][j] = Integer.MAX_VALUE;
            }
        }

        int answer = Integer.MAX_VALUE;
        for (int j = 0; j < n; j++) {
            answer = Math.min(dfs(n - 1, j), answer);
        }
        return answer;
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0) return Integer.MAX_VALUE / 2;
        else if (cache[i][j] != Integer.MAX_VALUE) return cache[i][j];
        else if (i == 0) return matrix[i][j];
        else if (j == 0) return cache[i][j] = Math.min(dfs(i - 1, j), dfs(i - 1, j + 1)) + matrix[i][j];
        else if (j == matrix.length - 1) return cache[i][j] = Math.min(dfs(i - 1, j), dfs(i - 1, j - 1)) + matrix[i][j];
        else
            return cache[i][j] = Math.min(Math.min(dfs(i - 1, j), dfs(i - 1, j - 1)), dfs(i - 1, j + 1)) + matrix[i][j];
    }

    /**
     * 2. 迭代
     */
    public int minFallingPathSum2(int[][] matrix) {
        int n = matrix.length;
        if (n == 1) return matrix[0][0];
        int[][] f = new int[n + 1][n + 2];
        f[0][0] = Integer.MAX_VALUE / 2;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0) f[i + 1][j + 1] = matrix[i][j];
                else if (j == 0) f[i + 1][j + 1] = Math.min(f[i][j + 1], f[i][j + 2]) + matrix[i][j];
                else if (j == matrix.length - 1) f[i + 1][j + 1] = Math.min(f[i][j + 1], f[i][j]) + matrix[i][j];
                else f[i + 1][j + 1] = Math.min(Math.min(f[i][j + 1], f[i][j]), f[i][j + 2]) + matrix[i][j];
            }
        }

        int answer = Integer.MAX_VALUE;
        for (int j = 0; j < n; j++) {
            answer = Math.min(f[n][j + 1], answer);
        }
        return answer;
    }
}
